<?php
namespace App\Http\Controllers\Admin;

use App\Service\Admin\GoodsCateService;
use Illuminate\Http\Request;

class GoodsCateController extends BaseController
{
    //商品分类

    public function __construct(GoodsCateService $service)
    {
        $this->db = $service;
    }

    //列表
    public function getIndex()
    {
        $res = $this->db->getList();
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson(0, '', $res['data'], $res['total']);
    }

    //选项
    public function getOption()
    {
        $res = $this->db->getOption();
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson(0, '', $res['data']);
    }

    //一个
    public function getOne(Request $request)
    {
        $id = $request->post('id', 0);
        $res = (new GoodsCateService())->getOne($id);
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson(0, '', $res['data']);
    }

    //保存
    public function save(Request $request)
    {
        $id = $request->post('id', 0);
        $pas['title'] = $request->post('title', '');
        $pas['img'] = $request->post('img', '');
        $pas['pid'] = $request->post('pid', 0);
        if (!$pas['title']) {
            return $this->toJson(-2, '图标分类名必须的');
        }
        if ($id) {
            if (!$pas['img']) {
                return $this->toJson(-2, '图标必须的');
            }
            $res = (new GoodsCateService())->modify($id, $pas);
        } else {
            $res = (new GoodsCateService())->addOne($pas);
        }
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson();
    }

    //删除
    public function setDel(Request $request)
    {
        $id = $request->post('id', 0);
        $res = (new GoodsCateService())->setDel($id);
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson();
    }

    //导出功能，已废弃
    public function getOut(Request $request)
    {
        $res =(new GoodsCateService())->getClist();
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        $res = $res['data'];
        $titles = ['分类名称', '图标', '父级名', '最近时间',];
        $fname = 'daochu/sccate-'.time().'.txt';
        file_put_contents($fname, implode('<-->', $titles).PHP_EOL, FILE_APPEND);
        foreach ($res as $v) {
            $arys = [
                $v['title'], $v['img'], $v['pname'], $v['uptime'],
            ];
            file_put_contents($fname, implode('<-->', $arys).PHP_EOL, FILE_APPEND);
        }
        $fpath = env('DOMAIN').'/'.$fname;
        return $this->toJson(0, '', $fpath);
    }
}